<template>
    <div class="clock"><p>倒计时</p>{{rest}}秒</div>
</template>

<script>
export default {
    props: ['max'],

    data() {
        return {
            begin: 0,
            cur: 0,
            last: 0,
            timer: null,
        }
    },
    computed:{
        rest(){
            return Math.ceil((this.max * 1000 - 1000 - (this.cur - this.begin)) / 1000)
        }
    },
    methods: {
        timeup(){
            // 时间到
            clearInterval(this.timer);
            this.$emit('timeup');
            this.cur = this.begin = new Date().getTime();
        },
        tick(){
            // 获取本地时间
            let now = new Date().getTime();
            // 对比时间差
            if(now - this.cur < 0 || now - this.begin > this.max * 1000){
                // 时间被篡改 || 时间到
                this.timeup();
            } else {
                this.cur = now;
            }

        },
        start(){
            // 开始
            this.cur = this.begin = new Date().getTime();
            this.timer = setInterval(this.tick, 50);
        },
        stop(){
            clearInterval(this.timer)
            this.cur = this.begin = new Date().getTime();
        },
        pause(){
            clearInterval(this.timer)
        },
        restart(){
            // 重启计时器
            clearInterval(this.timer)
            this.cur = this.begin = new Date().getTime();
            this.timer = setInterval(this.tick, 50);

        },
        getRest(){
            return Math.ceil((this.max * 1000 - 1000 - (this.cur - this.begin)) / 1000)
        }
    },
    mounted: function() {
        // this.rest = this.max - 1;
        // this.begin();
    }

};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
    .clock{
        width: 1.48rem;
        height: 1.69rem;
        text-align: center;
        background: url('./clock.png') no-repeat;
        background-size: 100%;
        box-sizing: border-box;
        padding-top: .65rem;
        font-weight: 600;
        font-size: .3rem;
        color: #c34197;
        p{
            font-size: .25rem;
            font-weight: 400;
            margin-bottom: .04rem;
            color: #000;
        }
    }
</style>
